<template>
  <div class="item">
    <div class="item-text">
      <input
        type="checkbox"
        :checked="item.isDone"
        @change="
          $emit('checkChange', { id: item.id, isDone: $event.target.checked })
        "
      />
      <div
        v-if="!isEdit"
        class="text"
        :class="{ done: item.isDone }"
        @dblclick="handlerDblclick('dbl', item)"
      >
        {{ item.text }}
      </div>
      <input
        v-else
        class="text"
        type="text"
        ref="input"
        @blur="handlerDblclick('blur')"
        v-model="text"
        @keydown.enter="handleChange({ text, id: item.id })"
      />
    </div>
    <div class="delete" @click="$emit('deleteItem', item.id)">X</div>
  </div>
</template>

<script>
export default {
  props: {
    item: {
      type: Object,
    },
  },
  data() {
    return {
      isEdit: false,
      text: "",
    };
  },
  methods: {
    handleChange(all) {
      this.$emit("handleChange", all);
      this.$refs.input.blur();
    },
    handlerDblclick(type, item) {
      this.isEdit = !this.isEdit;
      if (type == "blur") return;
      this.text = item.text;
      this.$nextTick(() => {
        this.$refs.input.focus();
      });
    },
  },
};
</script>

<style scoped>
.item {
  margin-top: 8px;
  display: flex;
  width: 300px;
  height: 50px;
  max-width: 100%;
  justify-content: space-between;
  align-items: center;
}
.done {
  color: #ccc;
  text-decoration: line-through;
}
.item-text {
  display: flex;
  flex-grow: 1;
  align-items: center;
}
.text {
  flex-grow: 1;
  outline: none;
  height: 20px;
  margin: 0 4px;
}
.delete {
  cursor: pointer;
  width: 20px;
  height: 20px;
  border-radius: 4px;
  line-height: 20px;
  text-align: center;
  background-color: red;
  color: #fff;
  font-size: 14px;
}
</style>